import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import AudDialog from '@/pages/components/Aud/AudDialog';
import { LoadIndicator } from 'devextreme-react';
import AdjustLeftTree from './components/AdjustLeftTree';
import AdjustEntry from './components/AdjustEntry';
import { DevToolBar, CpasIcon, LayoutB, DevPopup, } from '~/public/cpas-ui';
import { Item } from 'devextreme-react/toolbar';
import notify from 'devextreme/ui/notify';
import { delArray, moneyFormat, numberTotalMethod, pushNumberData } from '@/utils';
import { Guid, guid } from 'guid-factory/lib/Guid';
import { DelZBAdjustBatch, ZBAdjustBill, detailDel, mergeList, reCaljustBill, rollBillsOne, subjectGetJZKM } from './service';
import { useModel } from 'umi';
import { ZBAdjust } from '../../AdjustToolBar/service';
import { ZBAdjustDel, getOneBillDetail, getReportItemsData, rollBills } from '../service';
import ClassiFication from './components/AdjustEntry/components/ClassiFication';
import { AdjustingEntryClearTempTable, ZBAdjustCancel } from './components/AdjustEntry/service';
import BigNumber from 'bignumber.js';

import BatchAddSubjectPopup from './batchAddSubjectPopup';



import SavePopup from './components/AdjustEntry/components/SavePopup';
import EntryPopup from './components/AdjustEntry/components/EntryPopup';


const SpecificPupopContext = React.createContext({});


const SpecificPupopFun = React.forwardRef((props: any, ref) => {

  const { isShowGloablLoad, setIsShowGlobalLoad } = useModel('useAdjustModel');
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurUser & any;
  const { AddClickRef, whereFrom, refreshClick } = props;

  const [popupVisible, setPopupVisible] = useState<boolean>(false);
  // const [batchAddSubjectPopupVisible, setBatchAddSubjectPopupVisible] = useState<boolean>(false);


  const diaParams = useRef<any>();

  const AdjustLeftTreeRef = useRef<any>();
  const AdjustEntryRef = useRef<any>();
  const classiFicationRef = useRef<any>();
  const ErrorPopupRef = useRef<any>();
  const EntryPopupRef = useRef<any>();
  const ShutDownRef = useRef<any>();
  const batchAddSubjectPopupRef = useRef<any>();



  // const [isShowGloablLoad, setIsShowGlobalLoad] = useState<boolean>(false);
  // const [entryParamData.toolBarNotSave, settoolBarNotSave] = useState<boolean>(true); //  工具条状态控制
  const ToolBarStyle: React.CSSProperties = { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' };
  const ToolBarTextStyle: React.CSSProperties = { marginTop: '5px' };
  const DeleteEntryRef = useRef<any>();
  const [cellClickData, setCellClickData] = useState<any>({});
  // const [devTableData_ID, setDevTableData_ID] = useState<string>('');

  const [contentError, setContentError] = useState<string>('');

  /**------------ 审计用到的属性 start  ------------**/
  const [entryParamData, setEntryParamData] = useState<any>({
    TZLXtypeName: '账项调整',
    adjustTSClassName: '会计差错更正',
    adjustTSClassID: '1',
    adjustChanged: '',
    adjustChangedName: "期末",
    TZLXtypeID: '',
    // adjustShowStateSJ: false,
    jzsbqqcVal: true,
    isTZVal: true,
    curDataBillID: '',
    oldBillIDDbName: '',
    newYearSelectText: '',
    remarksMemo: '',
    rollingData: {},
    curDataYearData_ID: '',
    billNoBHNumber: '',
    toolBarNotSave: false,
    rollBillState: false,
    isEdit: false
  });
  const curDataBillIDRef = useRef<any>('');
  // const [curBillID, setCurBillID] = useState<string>('');

  /**------------ 审计用到的属性 end  ------------**/

  const changeEntryParamData_fun = (changeData: any, isFrist: boolean = false) => {

    if (!isFrist) {
      changeData = { ...changeData, toolBarNotSave: false }
    }
    // debugger;
    setEntryParamData((oldData: any) => {
      const newData = {
        ...oldData, ...changeData
      };
      curDataBillIDRef.current = newData.curDataBillID;
      return newData;
    });
  }

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: (params: any) => {
      console.log(params, '@@@');
      // // setIsShowGlobalLoad(true); 
      setPopupVisible(true);
      setIsShowGlobalLoad(true);
      // changeEntryParamData_fun({
      //   curDataBillID: params.args.dataBillID,
      //   oldBillIDDbName: params.args.dataBillID,
      //   toolBarNotSave: params.args.state,
      //   isEdit: params.args.state,
      //   curDataYearData_ID: params.args.Data_ID,
      //   adjustChanged: `${params.args.isTZQJ}`,
      //   adjustChangedName: params.args.isTZQJ === '0' ? "期初" : "期末",
      //   remarksMemo: '',
      //   rollBillState: false,
      // }, true);
      // setDevTableData_ID(params.args.Data_ID);

      // setDevTableData_ID(diaParams.current.args.Data_ID);
      diaParams.current = params;

    },


    newAddDanJu: (params: any) => {
      changeEntryParamData_fun({
        curDataBillID: params.args.dataBillID,
        oldBillIDDbName: params.args.dataBillID,
        toolBarNotSave: params.args.state,
        isEdit: params.args.state,
        remarksMemo: '',
      }, true);
      setTimeout(() => {
        setIsShowGlobalLoad(false);
      }, 300);
    },
  }));

  const treeNodeCellDblClick = (nodeData: any) => {
    AdjustEntryRef.current.treeDblClickGetGridData(nodeData);
    changeEntryParamData_fun({
      toolBarNotSave: false,
    });
  }

  const treeSelectCellClick = (nodeData: any) => {
    setCellClickData(nodeData);
  }

  const getAdjustRightTableRef = () => {
    const TableRef = AdjustEntryRef.current.openAdjustTableRef();
    return TableRef;
  }

  // 新增分录
  const EntryAdd = async () => {
    const cellClickDataTemp = await AdjustLeftTreeRef.current.addSelectNodeFun();
    console.log(cellClickDataTemp, '@@@ cellClickData');
    if (!cellClickData?.ID || !cellClickDataTemp?.ID) return notify('请选择您要添加的数据', 'warning', 2000);
    const myId: guid = Guid.newGuid();
    let source8: any;
    let cellDbData: any;
    const source1 = cellClickDataTemp;
    const source2 = { XH: cellClickDataTemp.rowIndex }; //序号
    const source3 = { DF: null }//贷方
    const source4 = { JF: null }; //借方
    const source5 = { remark: '' }; //备注
    const source6 = { GUID: myId }; //GUID
    const source7 = { billID: entryParamData.curDataBillID }; //billID
    if (whereFrom === '账表调整') {
      source8 = { isHCFSE: 0 }; //红冲
      cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6, source8);
    } else {
      cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6);
    };
    console.log(cellDbData, '@@@ cellDbData');

    AdjustEntryRef.current.treeDblClickGetGridData(cellDbData);
    changeEntryParamData_fun({
      toolBarNotSave: false
    });
  };
  // 删除分录
  const DeleteLine = (data: any, dataIndex: number) => {
    // 获取GUID
    const tableData = AdjustEntryRef.current.getdbClickDevData();
    // 过滤数据 实现批量删除
    DeleteEntryRef.current.show({
      title: "提示",
      okCallback: async () => {
        const r = await detailDel(whereFrom, {
          dbname,
          billID: curDataBillIDRef.current,
          GUID: data.GUID
        });
        // console.log(r, '@@@ ');

        if (r) {
          const newData = delArray(tableData.AdjustTableData, 'GUID', data.GUID);
          changeEntryParamData_fun({
            toolBarNotSave: false,
          });
          // 更新后续数据的 XH 值
          for (let i = dataIndex; i < newData.length; i++) {
            newData[i].XH = i + 1;
          }
          AdjustEntryRef.current.setdbClickDevDataRef(newData);
        }
      }
    })
  };
  // 删除分录
  const EntryDelete = () => {

    const TableRef = getAdjustRightTableRef();

    const tableData = AdjustEntryRef.current.getdbClickDevData();

    if (tableData.NewRowIndexRef <= -1) return notify("请选择您要删除的分录", "warning", 2000);
    if (tableData.AdjustTableData.length === 0) return;
    // 获取GUID
    const ranges = TableRef.getSelectCellRange();
    if (ranges.length) {
      const guid = ranges.map((item: any) => item.GUID);
      DeleteLine({ GUID: guid[0] }, tableData.NewRowIndexRef);
    } else {
      notify("请选择您要删除的分录", "warning", 2000);
    }
  };

  const RecountEvent = async () => {

    const r = await ZBAdjust(whereFrom, {
      dbname,
      Data_ID: entryParamData.curDataYearData_ID,
      editUser: username
    })
    if (r) {
      notify('金额调整成功', 'success', 2000)
    }
  };

  const getOneBillDetailRefresh = async (data: any) => {
    const r = await getOneBillDetail(whereFrom, {
      dbname,
      billID: data,
      isRefresh: true,
    });
    return r.data;
  }

  // 负值重分类 *
  const FicaTionClick = async () => {

    setIsShowGlobalLoad(true);
    setTimeout(() => {
      classiFicationRef.current?.show({
        Data_ID: entryParamData.curDataYearData_ID,
        EntryName: entryParamData.newYearSelectText,
        okCallback: async () => {
          setIsShowGlobalLoad(true);
          let changeObj: any = { toolBarNotSave: false };
          const res = await getOneBillDetailRefresh(entryParamData.curDataBillID);
          let newarr: any[] = [];
          const newGUIDList = mergeList(newarr, res);
          newarr = newGUIDList.map(guid => newarr.find(item => item.GUID === guid) || res.find(item => item.GUID === guid)).filter(Boolean);
          if (whereFrom === '审计调整') {
            changeObj = {
              ...changeObj,
              TZLXtypeName: '报表调整',
              TZLXtypeID: '3'
            };
          } else {
            changeObj = {
              ...changeObj,
              TZLXtypeID: '1',
              TZLXtypeName: ''
            };
          }
          AdjustEntryRef.current.setdbClickDevDataRef(newarr);
          changeEntryParamData_fun(changeObj);
          setIsShowGlobalLoad(false);
        },
        cancelCallback: () => {
          setIsShowGlobalLoad(false);
        }
      });
    }, 500);
  };

  const changeCategoryMenuOptions = {
    items: [
      {
        icon: 'iconfont icon-fujiagongneng',
        items: [
          // {
          //   ID: "0",
          //   text: '转为审计调整',
          // },
          // {
          //   ID: "1",
          //   text: '重新排序',
          // },
          {
            ID: "2",
            text: '设置自动结转科目',
          },
          {
            ID: "3",
            text: '批量选择科目',
          },
          {
            ID: "4",
            text: '批量删除',
          },
        ],
      },
    ],
    onItemClick: async (e: any) => {
      switch (e.itemData.ID) {
        case '0': {
          // 账表调整分录 // AdjustEntry
          // EntryRef.current.show({
          //   args: { dataBillID: dataBillID, state: false, itemNames: periodName, adjustShowStates: periodName == "期初" ? true : false }
          // });
          // setTimeout(() => {
          //   setPopupVisible(false);
          // }, 300)
        }
          break;
        case '2': {
          const r = await subjectGetJZKM({
            dbname,
            Data_ID: entryParamData.curDataYearData_ID,
          })
          EntryPopupRef.current.show({
            args: {
              title: '设置自动结转科目',
              data: r,
              tipNotify: false
            },
            okCallback: () => {
            },
          })
        }
          break;
        case '3': {

          // setBatchAddSubjectPopupVisible(true);
          batchAddSubjectPopupRef.current.show({
            args: {
              title: '批量设置科目',
              Data_ID: entryParamData.curDataYearData_ID,
            },
            okCallback: async (treeData: any[]) => {
              // console.log(treeData, '@@@ treeData');
              const resTreeBatch = await AdjustEntryRef.current.treeBatchGetGridData(treeData);
              if (resTreeBatch) {
                changeEntryParamData_fun({
                  toolBarNotSave: false
                });
              }
              return resTreeBatch;
            },
            cancelCallback: () => {
              // setBatchAddSubjectPopupVisible(false)
            },
          })
        };
          break;
        case '4': {
          const TableRef = getAdjustRightTableRef();
          // 获取GUID
          const ranges = TableRef.getSelectCellRange();
          const tableData = AdjustEntryRef.current.getdbClickDevData();
          if (tableData.length === 0) return notify("请选择您要删除的分录", "warning", 2000);
          if (ranges.length) {
            // 批量删除
            const guidData = ranges.map((item: any) => {
              return { GUID: item.GUID, rowState: 'delete' }
            });
            // const guidDataJion = guidData.join(';');

            DeleteEntryRef.current.show({
              title: "批量删除提示",
              okCallback: async () => {
                const resDel = await DelZBAdjustBatch(dbname, entryParamData.curDataBillID, guidData)
                if (resDel.success) {
                  await AdjustEntryRef.current.getOneBillDetailsRef(entryParamData.curDataBillID, true);
                }
              }
            });
          } else {
            notify("请选择您要删除的分录", "warning", 2000);
          }
        };
          break;
      }
    },
  };

  // 新增单据
  const DocumentAdd = useCallback(() => {
    setIsShowGlobalLoad(true);
    AdjustEntryRef.current.setdbClickDevDataRef([]);
    AddClickRef(true);
  }, [AdjustEntryRef.current]);


  function calculateSumAndCompare(dataList: any) {
    if (dataList.length === 0) return true;
    const dataListKeys = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8', 'Y9', 'Y10'];
    const dataJudge = new Set();
    for (let index = 0; index < dataList.length; index++) {
      const tempObj = dataList[index];
      let totalY1_result = new BigNumber(0.00);
      for (const propName of dataListKeys) {
        if (tempObj.hasOwnProperty(propName)) {
          totalY1_result = totalY1_result.plus(tempObj[propName] || 0);
        }
      }
      const totalY1_res: any = pushNumberData(`${totalY1_result}` || '0');
      console.log(tempObj, tempObj?.DF, tempObj?.JF, totalY1_res, '@@@ calculateSumAndCompare');
      if (tempObj?.DF === Number(totalY1_res.truncatedNumber) || tempObj?.JF === Number(totalY1_res.truncatedNumber)) {
        dataJudge.add(true);
      } else {
        dataJudge.add(false);
      }
    }
    const dataJudgeArr = Array.from(dataJudge);
    console.log(dataJudgeArr, dataJudge, '@@@ dataJudge');
    if (dataJudgeArr.length === 1 && dataJudgeArr[0]) {
      return true;
    }
    return false;
  }

  const getOneBillDetailData = async (data: any) => {
    const r = await getOneBillDetail(whereFrom, {
      dbname,
      billID: data,
      isRefresh: true,
    });
    return r.data;
  }

  // 执行重算方法
  const actionReCalBill = async () => {
    const res = await reCaljustBill({
      Data_ID: entryParamData.curDataYearData_ID,
      dbname,
      editUser: username,
      isRecalTZ: true
    });
    if (!res.success) {
      notify(`重算失败${res.data}`, 'error', 2000);
    }
  }

  const successFunction = () => {
    notify('保存成功', 'success', 2000);
    changeEntryParamData_fun({
      toolBarNotSave: true
    }, true);
    setIsShowGlobalLoad(false);
    refreshClick();
  };
  // 设置自动结转科目
  const settingZDJZKM = useCallback(async (tempData: any) => {
    setIsShowGlobalLoad(false);
    const res = await subjectGetJZKM({
      dbname,
      Data_ID: entryParamData.curDataYearData_ID
    });
    EntryPopupRef.current.show({
      args: {
        title: '设置自动结转科目',
        data: res,
        tipNotify: true
      },
      // 点击确定的回调函数 获取回掉数据时间节点返回需要的
      okCallback: async () => {
        setIsShowGlobalLoad(true);
        const rs = await ZBAdjustBill(whereFrom, tempData);
        if (rs.success) {
          successFunction();
          AdjustEntryRef.current.getOneBillDetailOfJZDataRef();
        }
        setIsShowGlobalLoad(false);
      },
    });
  }, [whereFrom, entryParamData]);
  // 账表调整、审计调整
  const methodEvent = useCallback(async () => {
    setIsShowGlobalLoad(true);
    let tempZBAdObjb: any = {};
    const ress = await getOneBillDetailData(entryParamData.curDataBillID);
    const DataFilter = ress.filter(item => item.ZLArea === "已维护");
    const a1 = calculateSumAndCompare(DataFilter);
    console.log(a1, DataFilter, '@@@ a1 DataFilter------------');

    tempZBAdObjb = {
      dbname,
      billID: entryParamData.curDataBillID,
      Data_ID: entryParamData.curDataYearData_ID,
      billNo: entryParamData.billNoBHNumber,
      TZLX: entryParamData.TZLXtypeID,
      TZQJ: entryParamData.adjustChanged,
      isTZ: `${entryParamData.isTZVal}`,
      remarks: entryParamData.remarksMemo,
      editUser: username
    }

    if (whereFrom === '审计调整') {
      tempZBAdObjb = {
        ...tempZBAdObjb,
        isRetrospect: entryParamData.adjustChangedName === "期初" ? `${entryParamData.jzsbqqcVal}` : "",
        adjustType: entryParamData.adjustTSClassID
      }
    }
    console.log(tempZBAdObjb, entryParamData, '@@@');
    if (a1) {
      const r = await ZBAdjustBill(whereFrom, tempZBAdObjb);
      if (r.success) {
        actionReCalBill();
        successFunction();
        if (!entryParamData.rollBillState) {
          AdjustEntryRef.current.getOneBillDetailOfJZDataRef();
        }
      } else {
        if (r.data === "【50001】【未设置结转科目】该调整分录包含损益类科目，无法自动结转损益！") {
          settingZDJZKM(tempZBAdObjb);
        } else {
          notify(`保存失败${r.data}`, 'error', 2000);
        }
      }
    } else {
      notify("请检查已维护的账龄区间设置是否正确", 'error', 2000)
    }
    setIsShowGlobalLoad(false);
  }, [AdjustEntryRef.current, entryParamData, whereFrom, username]);

  // 保存单据
  const DocumentSave = async () => {
    setIsShowGlobalLoad(true);
    const TableRef = getAdjustRightTableRef();
    await TableRef.instance.saveEditData();

    const tableData = AdjustEntryRef.current.getdbClickDevData();
    const { dbClickDevData } = tableData;
    let sumDF = ''
    let sumJF = '';
    let isHCFSECEStr = ' ';// 是否红冲的差额
    if (whereFrom === '账表调整' && entryParamData.adjustChanged === '0') {
      const isHCFSETotal = numberTotalMethod(dbClickDevData, true);
      console.log(isHCFSETotal);
      const isHCFSECE = isHCFSETotal.totaljF_resNumber - isHCFSETotal.totaldF_resNumber; // 借方 减去 贷方
      isHCFSECEStr = moneyFormat(isHCFSECE);
    }
    const DataMap = dbClickDevData.map((item: any) => {
      if (!item?.DF && !item?.JF || item?.DF && item?.JF) return true;
      return item?.DF == item?.JF;
    });
    const resTotal = numberTotalMethod(dbClickDevData);
    sumDF = resTotal.totaldF_res;
    sumJF = resTotal.totaljF_res;
    AdjustEntryRef.current.setdbClickDevDataRef(dbClickDevData);
    // const allItemsValid = dbClickDevData.every((item: any) => (!item?.KMBH || !item?.itemNames3 || !item?.KMMC));
    let allItemsValidData = [];
    for (let index = 0; index < dbClickDevData.length; index++) {
      const item = dbClickDevData[index];
      if (!item?.KMBH || !item?.itemNames3 || !item?.KMMC) {
        allItemsValidData.push(true);
      }
    }
    allItemsValidData = [...new Set(allItemsValidData)];
    if (allItemsValidData.length > 0) {
      setIsShowGlobalLoad(false);
      return notify(`调整的分录没有报表项目、科目编号和科目名称，不允许保存请检查`, "warning", 2000);
    }

    const arr = [...new Set(DataMap)];
    if (dbClickDevData.length) {
      const filteredIndexes = dbClickDevData.reduce((acc: number[], item: any, index: number) => {
        if (!item?.DF && !item?.JF) {
          acc.push(index + 1);
        }
        return acc;
      }, []);
      if (filteredIndexes?.length === 0) {
        console.log(sumDF, sumJF, 'sumDF----------');
        if (!sumDF && !sumJF) {
          setContentError("未输入调整金额")
          ErrorPopupRef.current.show({
            title: "错误",
            onToolbardisplay: true,
            okCallback: () => { setIsShowGlobalLoad(false); },
            onCancel: () => {
              setIsShowGlobalLoad(false);
            },
          })
        } else {
          if (sumDF === sumJF) {
            if (arr[0] || arr[1]) {
              setContentError("借方金额 和 贷方金额不能同时输写!")
              ErrorPopupRef.current.show({
                title: "错误",
                onToolbardisplay: true,
                okCallback: () => { setIsShowGlobalLoad(false); },
                onCancel: () => {
                  setIsShowGlobalLoad(false);
                },
              });
            } else {

              if (whereFrom === '账表调整' && entryParamData.adjustChanged === '0' && isHCFSECEStr !== " ") {
                setIsShowGlobalLoad(false);
                return notify(`红冲本期借贷方金额不相等，差额【${isHCFSECEStr}】，请检查`, "warning", 2000);
              }
              methodEvent();
            }
          } else {
            setContentError("借贷方金额不相等,无法保存此单据")
            ErrorPopupRef.current.show({
              title: "错误",
              onToolbardisplay: true,
              okCallback: () => { setIsShowGlobalLoad(false); },
              onCancel: () => {
                setIsShowGlobalLoad(false);
              },
            })
          }
        }
      } else {
        notify(` 以下序号记录【${filteredIndexes}】未输入调整金额!`, "warning", 3000);
        setIsShowGlobalLoad(false);
      }
    } else {
      setContentError("未录入调整分录明细，无法保存此单据")
      ErrorPopupRef.current.show({
        title: "错误",
        onToolbardisplay: true,
        okCallback: () => { setIsShowGlobalLoad(false); },
        onCancel: () => {
          setIsShowGlobalLoad(false);
        },
      })
    }
  }
  // useCallback(, [AdjustEntryRef.current, entryParamData, whereFrom, getAdjustRightTableRef, methodEvent]);

  // 单个滚调
  const RollingClick = useCallback(async () => {
    if (!entryParamData.curDataBillID) return;
    // changeEntryParamData_fun({
    //   toolBarNotSave: false,
    //   rollBillState: true,
    // });
    setIsShowGlobalLoad(true);

    const myTempGuid: guid = Guid.newGuid();

    const r = await rollBillsOne(whereFrom, {
      orgBillID: entryParamData.curDataBillID,
      dbname,
      billID: myTempGuid,
      trueName: username,
      userCode: usercode
    });
    if (r.success) {
      let resTempData = r.data[0];
      // if (resTempData?.isExistsNoneKM === 1) {
      //   notify("滚调的分录中存在不连续的科目，请自行修改！", "error", 2000);
      //   changeEntryParamData_fun({
      //     toolBarNotSave: true,
      //     rollBillState: false,
      //     isTZVal: false,
      //   }, true);
      //   setIsShowGlobalLoad(false);
      //   return;
      // }
      if (resTempData.billID) {
        // const tempBillID = resTempData.billID;
        // notify("单据滚调成功！", "success", 2000);
        const newStr = entryParamData.newYearSelectText.replace(/\[(.*?)\]/, `[${resTempData?.Data_ID}]`);
        await AdjustEntryRef.current.getOneBillDetailsRef(myTempGuid, true);
        const tableData = AdjustEntryRef.current.getdbClickDevData();
        const { AdjustTableData } = tableData;
        let isTZQJ = '';
        let isTZQJName = '';
        if (resTempData.TZQJ === 1) {
          isTZQJ = "1";
          isTZQJName = "期末";
        } else {
          isTZQJ = "0";
          isTZQJName = "期初";
          const newDataDev = AdjustTableData.map((item: any) => {
            item.isHCFSE = resTempData?.TZLX === 0;
            return item;
          });
          AdjustEntryRef.current.setdbClickDevDataRef(newDataDev);
        }
        let TZLXStr = '';
        let adjustTypeStr = '';
        if (whereFrom === "审计调整") {
          if (resTempData.TZLX === 2) {
            TZLXStr = '账项调整';
          } else if (resTempData.TZLX === 3) {
            TZLXStr = '报表调整';
          } else if (resTempData.TZLX === 4) {
            TZLXStr = '其他调整';
          };
          if (resTempData.AdjustType === 1) {
            adjustTypeStr = '会计差错更正';
          } else if (resTempData.AdjustType === 2) {
            adjustTypeStr = '会计政策变更';
          } else if (resTempData.AdjustType === 3) {
            adjustTypeStr = '其他';
          } else {
            adjustTypeStr = '会计差错更正';
          };
          if (TZLXStr === '账项调整' || TZLXStr === '报表调整') {
            adjustTypeStr = '会计差错更正';
            resTempData.AdjustType === 1;
          } else {
            adjustTypeStr = '其他';
            resTempData.AdjustType === 3;
          }
        }
        let resChangeData: any = {
          adjustChanged: isTZQJ,
          adjustChangedName: isTZQJName,
          TZLXtypeName: whereFrom === "审计调整" ? TZLXStr : '',
          TZLXtypeID: `${resTempData?.TZLX}`,
          isTZVal: resTempData?.isTZ,
          curDataBillID: resTempData?.billID,
          remarksMemo: resTempData?.remarks,
          curDataYearData_ID: resTempData?.Data_ID,
          newYearSelectText: newStr,
          jzsbqqcVal: true,
          adjustTSClassName: whereFrom === "审计调整" ? adjustTypeStr : '',
          adjustTSClassID: whereFrom === "审计调整" ? `${resTempData?.AdjustType ?? 1}` : '',
          rollingData: resTempData,
          billNoBHNumber: resTempData?.billNo,
          toolBarNotSave: false,
          rollBillState: true,
        }
        // if (whereFrom === '审计调整') {
        //   resChangeData = { ...resChangeData, adjustShowStateSJ: resTempData?.TZQJ === 0 }
        // }
        changeEntryParamData_fun(resChangeData);

        // const res = await getReportItemsData(whereFrom, {
        //   dbname,
        //   billID: tempBillID
        // });
        // const resTempData = res[0];
        // if (resTempData?.Data_ID) {

        // } else {
        //   notify("不能正常获取下年度账套,无法滚调!", "error", 2000);
        //   changeEntryParamData_fun({
        //     toolBarNotSave: true,
        //   }, true);

        // }
        setIsShowGlobalLoad(false);
      } else {
        notify("单据滚调失败！", "error", 2000);
        console.log(r.data, '@@@ 这是返回值');
        changeEntryParamData_fun({
          toolBarNotSave: true,
          rollBillState: false,
          isTZVal: false,
        }, true);
        setIsShowGlobalLoad(false);

      }

    } else {
      notify(r.data, "error", 2000);
      changeEntryParamData_fun({
        toolBarNotSave: true,
        rollBillState: false,
        isTZVal: false,
      }, true);
      setIsShowGlobalLoad(false);
    }
  }, [whereFrom, entryParamData]);

  // 取消单据
  const DocumentCancel = useCallback(async () => {
    const tableData = AdjustEntryRef.current.getdbClickDevData();
    const { dbClickDevData } = tableData;
    if (dbClickDevData.length > 0) {
      ShutDownRef.current.show({
        title: "提示",
        okCallback: () => {
          DocumentSave();
          // setAddDataDF('0.00');
          // setAddDataJF('0.00');
        },
        noCallback: async () => {
          const r = await ZBAdjustCancel(whereFrom, {
            dbname,
            billID: curDataBillIDRef.current,
            Data_ID: entryParamData.curDataYearData_ID,
            editUser: username,
          })
          console.log(r, 'r---');
          setPopupVisible(false);
          AdjustingEntryClearTempTable({
            dbname,
            billID: curDataBillIDRef.current,
          })
        },
        cancelCallback: () => {
        }
      })
    } else {
      setPopupVisible(false);
    }
  }, [AdjustEntryRef.current, curDataBillIDRef.current, entryParamData, whereFrom]);

  const onReloadData = () => {
    setEntryParamData({
      TZLXtypeName: '账项调整',
      adjustTSClassName: '会计差错更正',
      adjustTSClassID: '1',
      adjustChanged: '',
      TZLXtypeID: '',
      // adjustShowStateSJ: false,
      jzsbqqcVal: true,
      isTZVal: true,
      curDataBillID: '',
      newYearSelectText: '',
      adjustChangedName: "期末",
      remarksMemo: '',
      rollingData: {},
      curDataYearData_ID: '',
      billNoBHNumber: '',
      toolBarNotSave: false,
      rollBillState: false,
    })
    ZBAdjustCancel(whereFrom, {
      dbname,
      billID: entryParamData.curDataBillID,
      Data_ID: entryParamData.curDataYearData_ID,
      editUser: username,
    });
    AdjustingEntryClearTempTable({
      dbname,
      billID: entryParamData.curDataBillID,
    });
    setPopupVisible(false);
  };

  // 删除单据
  const DocumentDelete = () => {

    DeleteEntryRef.current.show({
      title: "提示",
      okCallback: async () => {
        const r = await ZBAdjustDel(whereFrom, {
          dbname,
          billIDs: entryParamData.curDataBillID,
          editUser: username,
          Data_ID: entryParamData.curDataYearData_ID,
        });

        if (r) {
          notify('删除成功', 'success', 2000);
          onReloadData();
          refreshClick();
        } else {
          notify('删除失败', 'error', 2000);
        }
      }
    });
  };

  const onColsePupop = () => {
    console.log('@@@ onHidingdev 这是遮罩层点击事件');
    if (!AdjustEntryRef.current) return;
    const tableData = AdjustEntryRef.current.getdbClickDevData();
    const { dbClickDevData } = tableData;
    if (dbClickDevData?.length) {
      if (!entryParamData.toolBarNotSave) {
        console.log('@@@ onColsePupop 这是遮罩层判断参数', '进入提示');
        ShutDownRef.current?.show({
          title: "提示",
          okCallback: () => {
            DocumentSave();
          },
          noCallback: () => {
            onReloadData();
          },
          cancelCallback: () => {
          }
        });
        return;
      }
    }
    onReloadData();
    return;
  };

  const leftContainer = () => {
    return (
      <div style={{ width: '100%', height: '100%', padding: '8px' }}>
        <AdjustEntry
          ref={AdjustEntryRef}
          // devTableDataID={devTableData_ID}
          whereFrom={whereFrom}
          tableRowDel={DeleteLine}
          getCurDataBillIDRef={() => {
            return curDataBillIDRef.current
          }}
          changeEntryParamData={changeEntryParamData_fun}
        />
      </div>
    )
  }
  const rightContainer = () => {
    return (
      <div style={{ width: '100%', height: '100%', padding: '7px' }}>
        <AdjustLeftTree
          ref={AdjustLeftTreeRef}
          whereFrom={whereFrom}
          treeNodeCellDblClick={treeNodeCellDblClick}
          treeSelectCellClick={treeSelectCellClick}
        />
      </div>
    )
  }

  const layoutBContainer = useMemo(() => {
    if (popupVisible) {
      return <LayoutB
        rowSize={["10%", "70%", "80%"]}
        leftSlot={leftContainer()}
        rightSlot={rightContainer()}
      />
    }
    return <></>
  }, [popupVisible]);

  return (
    <>
      <AudDialog
        visible={popupVisible}
        title={diaParams.current?.args?.title}
        minWidth={1250}
        minHeight={730}
        height="85vh"
        width="95vw"
        showzuidahuaButton={true}
        showCancelButton={false}
        showOkButton={false}
        onHiding={() => {
          onColsePupop();
        }}

        onShown={() => {
          changeEntryParamData_fun({
            curDataBillID: diaParams.current.args.dataBillID,
            oldBillIDDbName: diaParams.current.args.dataBillID,
            toolBarNotSave: diaParams.current.args.state,
            isEdit: diaParams.current.args.state,
            curDataYearData_ID: diaParams.current.args.Data_ID,
            adjustChanged: `${diaParams.current.args.isTZQJ}`,
            adjustChangedName: diaParams.current.args.isTZQJ === '0' ? "期初" : "期末",
            remarksMemo: '',
            rollBillState: false,
          }, true);
        }}
      >
        <div style={{ position: "relative", width: '100%', height: '100%', display: 'flex', flexDirection: 'column', overflow: 'visible' }}>

          {isShowGloablLoad && <div style={{
            position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
            opacity: 0.5, zIndex: "99999", background: "#ddd"
          }}>
            <LoadIndicator id="medium-indicator" height={50} width={50} />
          </div>}
          <SpecificPupopContext.Provider value={{ entryParamData, setEntryParamData }}>
            <div style={{ width: '100%', height: '50px', display: 'flex', alignItems: 'center', justifyContent: "space-between", paddingBottom: '5px', borderBottom: "1px solid #ddd" }}>
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '' : '#ddd' }}>
                <span> <CpasIcon type='icon-zengjiadanju-copy-copy' fontSize={20} onClick={() => {
                  if (entryParamData.toolBarNotSave) {
                    DocumentAdd();
                  }
                }} /></span>
                <span style={{ marginTop: '5px' }}>新增单据</span>
              </div>
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '' : '#ddd' }}>
                <span> <CpasIcon type='icon-minus-circle' fontSize={20} onClick={() => {
                  if (entryParamData.toolBarNotSave) {
                    DocumentDelete();
                  }
                }} />  </span>
                <span style={{ marginTop: '5px' }}>删除单据</span>
              </div>
              <div style={{ border: "1px solid #f0ebeb", height: '72%', marginBottom: '5px' }} />
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '#ddd' : '' }}>
                <span><CpasIcon type='icon-baocun' fontSize={20} style={{ marginRight: '8px' }} onClick={() => {
                  if (!entryParamData.toolBarNotSave) {
                    DocumentSave();
                  }
                }} /></span>
                <span style={{ marginTop: '5px' }}>保存</span>
              </div>
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '#ddd' : '' }}>
                <span><CpasIcon type='icon-chexiao' fontSize={20} style={{ marginRight: '8px' }} onClick={() => {
                  if (!entryParamData.toolBarNotSave) {
                    DocumentCancel();
                  }
                }} /></span>
                <span style={{ marginTop: '5px' }}>取消</span>
              </div>
              <div style={{ border: "1px solid #f0ebeb", height: '72%', marginBottom: '5px' }} />
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '' : '#ddd' }} >
                <span>
                  <CpasIcon type='icon-refresh' fontSize={20} onClick={() => {
                    if (entryParamData.toolBarNotSave) {
                      AdjustEntryRef.current.DocumentRefreshRef();
                    }
                  }} />
                </span>
                <span style={{ marginTop: '5px' }}>刷新</span>
              </div>
              <div style={ToolBarStyle}>
                <span> <CpasIcon type='icon-xinzengfenlu' fontSize={20} style={{ marginRight: '8px' }} onClick={() => {
                  EntryAdd();
                }} /></span>
                <span style={ToolBarTextStyle}>新增分录</span>
              </div>
              <div style={ToolBarStyle}>
                <span> <CpasIcon type='icon-shanchufenlu' fontSize={20} style={{ marginRight: '8px' }}
                  onClick={() => {
                    EntryDelete();
                  }}
                /></span>
                <span style={ToolBarTextStyle}>删除分录</span>
              </div>
              <div style={ToolBarStyle}>
                <span><CpasIcon type='icon-fuzhizhongfenlei' onClick={
                  () => {
                    FicaTionClick();
                  }} fontSize={20} style={{ marginRight: '8px' }} /></span>
                <span style={ToolBarTextStyle}>负值重分类</span>
              </div>
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '' : '#ddd' }}>
                <span><CpasIcon type='icon-guntiao1' fontSize={20} onClick={
                  () => {
                    if (entryParamData.toolBarNotSave) {
                      RollingClick();
                    }
                  }} /></span>
                <span style={{ marginTop: '5px' }}>滚调</span>
              </div>
              <div style={{ border: "1px solid #f0ebeb", height: '72%', marginBottom: '5px' }} />
              <div style={{ ...ToolBarStyle, color: entryParamData.toolBarNotSave ? '' : '#ddd' }}>
                <span> <CpasIcon type='icon-zhongsuantiaozhengshu' onClick={() => {
                  if (entryParamData.toolBarNotSave) {
                    RecountEvent();
                  }
                }} fontSize={20} /></span>
                <span style={{ marginTop: '5px' }}>重算调整数</span>
              </div>
              <div style={{ border: "1px solid #f0ebeb", height: '72%', marginBottom: '5px' }} />
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }}>
                <DevToolBar.Default style={{ width: '100%', height: '31px' }}>
                  <Item widget="dxMenu" location="center" options={changeCategoryMenuOptions} cssClass='AgainMenu_Style' />
                </DevToolBar.Default>
                <span>附加功能</span>
              </div>
              <div style={{ width: '20%' }} />

            </div>
            <div style={{ height: 'calc(100% - 80px) ' }}>
              {layoutBContainer}
            </div>
            <BatchAddSubjectPopup whereFrom={whereFrom} ref={batchAddSubjectPopupRef} />
          </SpecificPupopContext.Provider>
        </div>
      </AudDialog>

      <EntryPopup ref={EntryPopupRef} width={500} height={300} AccountDataID={entryParamData.curDataYearData_ID} />
      <SavePopup ref={ShutDownRef} whereFrom={whereFrom} width={400} height={200} />

      <DevPopup.Default ref={ErrorPopupRef} width={80} height={220} >
        {() => {
          return <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ width: '40px', height: '40px', borderRadius: '50%', border: '2px #ddd solid', background: 'red', marginRight: '10px' }}><CpasIcon type='icon-close1' fontSize={35} color="#fff" /></span>
            <span>{`${contentError}`}</span>;
          </div>
        }}
      </DevPopup.Default>
      <DevPopup.Default ref={DeleteEntryRef} width={80} height={200} >
        {() => {
          return <span>确定要执行此操作吗？</span>
        }}
      </DevPopup.Default>
      <ClassiFication ref={classiFicationRef} BillID={entryParamData.curDataBillID} isQC={entryParamData.adjustChanged === "0"} width={1250} height={730} />




    </>
  );
});
export { SpecificPupopContext }; // 必须这样写 重要！
export default SpecificPupopFun;

